﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MediSIIM.BizComponent.HangZhouYHQYB;
using SWSoft.Framework;
using YUHANGMLDZ.Entities;
using System.Reflection.Emit;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Reflection;
using SWSoft;
using Tools.Unity;
using System.Xml.Serialization;

namespace YUHANGMLDZ
{
    public partial class FormYuHang : Form
    {
        public static YB_BXLBXX BXLBXX = Loader.GetLBXX("105");
        public FormYuHang()
        {
            InitializeComponent();
        }
        DalYB_ZLDMDZ zldmdz;
        DalYB_YPDMDZ ypdmdz;
        DalYB_JBDMDZ jbdmdz;
        private void btnzlload_Click(object sender, EventArgs e)
        {
            dgvzl.DataSource = zldmdz.GetList(zldmdz.YBZCBH, numericUpDown1.Value + 1);
            if (dgvzl.Rows.Count > 0)
            {
                btnzldz.Enabled = true;
            }
            string str = "hosp_code in (";
            foreach (DataRow item in (dgvzl.DataSource as DataTable).Rows)
            {
                str += "'0|" + item["YYYLXH"] + "',";
            }
            Debug.WriteLine(str.TrimEnd(',') + ")");
        }

        private void btnzldz_Click(object sender, EventArgs e)
        {
            btnzldz.Enabled = false;
            label2.Visible = true;
            try
            {
                #region 诊疗代码匹配
                var callparam = new HangZhouYHQYBTradeParms(100106);//项目匹配
                var table = ParamTable.NewTable();
                foreach (DataRow item in (dgvzl.DataSource as DataTable).Rows)
                {
                    var row = ParamTable.NewParamRow();
                    row["hospital_id"] = BXLBXX.YBYYDM;//医疗机构编码    
                    row["match_type"] = "0";//匹配类型
                    row["hosp_code"] = (zldmdz.MLDZQZ + "|" + item["YYYLXH"]).ToLower();//医院目录编码
                    row["hosp_name"] = item["MINGCHENG"].ToString();//医院目录名称
                    row["hosp_model"] = "无";//医院目录剂型
                    row["price"] = "";//单价
                    row["item_code"] = item["YBZLDM"].ToString().ToLower();//中心目录编码
                    row["item_name"] = item["ZLZWMC"].ToString();//中心目录名称
                    row["model_name"] = "无";//中心目录剂型
                    row["effect_date"] = DateTime.Now.ToString("yyyy-MM-dd");//生效日期
                    row["expire_date"] = "2099-01-01";//失效日期
                    row["edit_staff"] = "DBA";//操作员工号
                    row["edit_man"] = "管理员";//操作员姓名
                    table.AddRow(row);
                }
                callparam["matchinfo"] = table;
                callparam.SetOutResult("matchitem", "notvalidlist");
                try
                {
                    Util.YBCall(callparam);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                if (callparam.OutputTable.ContainsKey("notvalidlist"))
                {
                    BindTable(dgvzl, callparam.OutputTable["notvalidlist"]);
                }
                ParamTable outtable;
                if (callparam.GetOutTable(out outtable, "matchitem"))
                {
                    zldmdz.Update(outtable);
                    MessageBox.Show("成功匹配 " + outtable.Rows.Count + " 个");
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            label2.Visible = false;
        }

        private void BindTable(DataGridView gridview, ParamTable paramTable)
        {
            if (paramTable != null)
            {
                gridview.DataSource = paramTable.TableView;
            }
        }

        private void dgvzl_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                //添加行号 
                SolidBrush v_SolidBrush = new SolidBrush(dgvzl.RowHeadersDefaultCellStyle.ForeColor);
                int v_LineNo = 0;
                v_LineNo = e.RowIndex + 1;

                string v_Line = v_LineNo.ToString();

                e.Graphics.DrawString(v_Line, e.InheritedRowStyle.Font, v_SolidBrush, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5);

            }
            catch (Exception ex)
            {
                MessageBox.Show("添加行号时发生错误，错误信息：" + ex.Message, "操作失败");
            }
        }

        private void FormYuHang_Load(object sender, EventArgs e)
        {
            Text = string.Format("{0}.{1}.{2} 医疗机构编码:{3}", BXLBXX.YLBXID, BXLBXX.YLBXMC, BXLBXX.YBYYMC, BXLBXX.YBYYDM);
            comboBox1.SelectedIndex = 0;
            try
            {
                zldmdz = new DalYB_ZLDMDZ();
                ypdmdz = new DalYB_YPDMDZ();
                jbdmdz = new DalYB_JBDMDZ();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void tabPage4_MouseClick(object sender, MouseEventArgs e)
        {

        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
        }

        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            dgvzl.Columns[e.Item.Index].Visible = e.Item.Checked;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            loadmatched(dgvzled, "0", txtzhenliao.Text);
        }

        public void loadmatched(DataGridView gridview, string name, string filter)
        {
            if (gridview.DataSource != null)
            {
                var dv = (gridview.Tag as DataTable).DefaultView;
                try
                {
                    dv.RowFilter = filter;
                    dgvzled.DataSource = dv;
                }
                catch (Exception)
                {
                    throw;
                }
            }
            else
            {
                var table = new DataTable();
                table.ReadXml(Application.StartupPath + "\\data\\" + name + ".xml");
                gridview.DataSource = table;
                gridview.Tag = table;
            }
            toolStripStatusLabel1.Text = gridview.Rows.Count.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            downmatched(dgvyibaoml, "0");
        }

        private void downmatched(DataGridView gridview, string type)
        {
            var datatable = new DataTable(type);
            var callparam = new HangZhouYHQYBTradeParms(100103);
            callparam[0]["hospital_id"] = BXLBXX.YBYYDM;
            callparam[0]["audit_status"] = "1";
            callparam[0]["item_type"] = type;
            callparam.SetOutResult("itemmatch");
            Util.YBCall(callparam);
            ParamTable table;
            if (callparam.GetOutTable(out table, "itemmatch"))
            {
                foreach (var item in table.Rows)
                {
                    foreach (var cname in item.Columns)
                    {
                        datatable.Columns.Add(cname.Name);
                    }
                    break;
                }
                foreach (var item in table.Rows)
                {
                    var newrow = datatable.NewRow();
                    foreach (var rowdata in item.Values)
                    {
                        if (datatable.Columns.Contains(rowdata.Key))
                        {
                            newrow[rowdata.Key] = rowdata.Value;
                        }
                    }
                    datatable.Rows.Add(newrow);
                }
            }
            if (!Directory.Exists(Application.StartupPath + "\\data\\"))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\data\\");
            }
            datatable.WriteXml(Application.StartupPath + "\\data\\" + type + ".xml", XmlWriteMode.WriteSchema);
            gridview.DataSource = datatable;
            gridview.Tag = datatable;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var table = (dgvzled.DataSource as DataView).ToTable();
            var sfd = new SaveFileDialog();
            sfd.Filter = "*.sql|*.sql";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                using (var sw = new StreamWriter(sfd.FileName))
                {
                    foreach (DataRow item in table.Rows)
                    {
                        sw.WriteLine(string.Format("UPDATE yb_zldmdz SET ybjyhm ='{0}'  WHERE ylbxid=105 AND yyylxh='{1}' AND ybzldm='{2}';",
                            item["serial_match"], item["hosp_code"].ToString().Split('|')[1], item["item_code"].ToString().ToUpper()));
                    }
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            var dalzldm = new DalYB_ZLDMDZ();
            string str = "hosp_code in (";
            foreach (DataRow item in dalzldm.GetList(1, 100).Rows)
            {
                str += "'0|" + item["YYYLXH"] + "',";
            }
            str = str.TrimEnd(',') + ")";
        }

        private void button7_Click(object sender, EventArgs e)
        {
            loadmatched(dgbyaopin, "1", txtyaopin.Text);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            downmatched(dgvyaopin, "1");
        }

        private void btnypload_Click(object sender, EventArgs e)
        {
            var table = ypdmdz.GetList(numericUpDown2.Value + 1);
            dgvyaopin.DataSource = table;
            string str = "hosp_code in (";
            foreach (DataRow item in table.Rows)
            {
                str += "'0|" + item["YYYPXH"] + "|" + item["YPCDDM"] + "',";
            }
            Debug.WriteLine(str.TrimEnd(',') + ")");
            if (dgvyaopin.Rows.Count > 0)
            {
                btnyppp.Enabled = true;
            }
        }

        private void dgvyaopin_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //添加行号 
            SolidBrush v_SolidBrush = new SolidBrush((sender as DataGridView).RowHeadersDefaultCellStyle.ForeColor);
            int v_LineNo = 0;
            v_LineNo = e.RowIndex + 1;

            string v_Line = v_LineNo.ToString();

            e.Graphics.DrawString(v_Line, e.InheritedRowStyle.Font, v_SolidBrush, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5);
        }

        private void button9_Click(object sender, EventArgs e)
        {
            var strs = "";
            foreach (DataRow item in (dgvzled.DataSource as DataView).ToTable().Rows)
            {
                strs += item["hosp_code"].ToString().Split('|')[1] + ",";
            }
            string str = "hosp_code in (";
            foreach (DataRow item in zldmdz.GetList(1, 100).Rows)
            {
                str += "'0|" + item["YYYLXH"] + "',";
            }
            str = str.TrimEnd(',') + ")";
            txtzhenliao.Text = str;
            button1_Click(sender, e);
        }

        private void btnyppp_Click(object sender, EventArgs e)
        {
            btnyppp.Enabled = false;
            label3.Visible = true;
            try
            {
                #region 药品代码匹配
                var callparam = new HangZhouYHQYBTradeParms(100106);//项目匹配
                var table = ParamTable.NewTable();
                foreach (DataRow item in (dgvyaopin.DataSource as DataTable).Rows)
                {
                    string ybyplx = "1";
                    if (item["YBYPLX"] != null)
                    {
                        ybyplx = item["YBYPLX"].ToString();
                    }
                    try
                    {
                        var row = ParamTable.NewParamRow();
                        row["hospital_id"] = BXLBXX.YBYYDM;//医疗机构编码    
                        row["match_type"] = ybyplx == "4" ? "3" : ybyplx;//匹配类型
                        row["hosp_code"] = (zldmdz.MLDZQZ + "|" + item["YYYPXH"] + "|" + item["YPCDDM"]).ToLower();//医院目录编码
                        row["hosp_name"] = item["MINGCHENG"].ToString();//医院目录名称
                        row["hosp_model"] = "无";//医院目录剂型
                        row["price"] = "";//单价
                        row["item_code"] = item["YBYPDM"].ToString().ToLower();//中心目录编码
                        row["item_name"] = item["YPZWMC"].ToString();//中心目录名称
                        row["model_name"] = "无";//中心目录剂型
                        row["effect_date"] = DateTime.Now.ToString("yyyy-MM-dd");//生效日期
                        row["expire_date"] = "2099-01-01";//失效日期
                        row["edit_staff"] = "DBA";//操作员工号
                        row["edit_man"] = "管理员";//操作员姓名
                        table.AddRow(row);
                    }
                    catch (Exception)
                    {
                    }
                }
                callparam["matchinfo"] = table;
                callparam.SetOutResult("matchitem","notvalidlist");
                try
                {
                    Util.YBCall(callparam);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                if (callparam.OutputTable.ContainsKey("notvalidlist"))
                {
                    BindTable(dgvyaopin, callparam.OutputTable["notvalidlist"]);
                }
                ParamTable outtable;
                if (callparam.GetOutTable(out outtable, "matchitem"))
                {
                    ypdmdz.Update(outtable, zldmdz.YBZCBH);
                    MessageBox.Show("成功匹配 " + outtable.Rows.Count + " 个");
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            label3.Visible = false;
        }

        private void btnjbload_Click(object sender, EventArgs e)
        {
            dgvjb.DataSource = jbdmdz.GetList(numericUpDown3.Value + 1);
            toolStripStatusLabel1.Text = dgvjb.Rows.Count + "";
            if (dgvjb.Rows.Count > 0)
            {
                btnjbpp.Enabled = true;
            }
        }

        private void btnjbpp_Click(object sender, EventArgs e)
        {
            btnyppp.Enabled = false;
            label5.Visible = true;
            Text = "开始匹配";
            try
            {
                #region 药品代码匹配
                var callparam = new HangZhouYHQYBTradeParms(100106);//项目匹配
                var table = ParamTable.NewTable();
                foreach (DataRow item in (dgvjb.DataSource as DataTable).Rows)
                {
                    var row = ParamTable.NewParamRow();
                    row["hospital_id"] = BXLBXX.YBYYDM;//医疗机构编码    
                    row["match_type"] = "4";//匹配类型
                    row["hosp_code"] = (zldmdz.MLDZQZ + "|" + item["YYJBDM"]).ToLower();//医院目录编码
                    row["hosp_name"] = item["YYJBMC"].ToString().Trim();//医院目录名称
                    row["hosp_model"] = "无";//医院目录剂型
                    row["price"] = "";//单价
                    row["item_code"] = item["YBJBDM"].ToString();//中心目录编码
                    row["item_name"] = item["JBZWMC"].ToString().Trim();//中心目录名称
                    row["model_name"] = "无";//中心目录剂型
                    row["effect_date"] = DateTime.Now.ToString("yyyy-MM-dd");//生效日期
                    row["expire_date"] = "2099-01-01";//失效日期
                    row["edit_staff"] = "DBA";//操作员工号
                    row["edit_man"] = "管理员";//操作员姓名
                    table.AddRow(row);
                }
                callparam["matchinfo"] = table;
                callparam.SetOutResult("matchitem", "notvalidlist");
                try
                {
                    Util.YBCall(callparam);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                ParamTable outtable;
                if (callparam.GetOutTable(out outtable, "notvalidlist"))
                {
                    BindTable(dgvjb, outtable);
                }
                if (callparam.GetOutTable(out outtable, "matchitem"))
                {
                    int count = jbdmdz.Update(outtable);
                    Text = ("成功匹配 " + count + " 个");
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            label5.Visible = false;
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //添加行号 
            AddRowCount(dgvzl, e);
        }

        private void AddRowCount(DataGridView dgv, DataGridViewRowPostPaintEventArgs e)
        {
            SolidBrush v_SolidBrush = new SolidBrush(dgv.RowHeadersDefaultCellStyle.ForeColor);
            int v_LineNo = 0;
            v_LineNo = e.RowIndex + 1;

            string v_Line = v_LineNo.ToString();

            e.Graphics.DrawString(v_Line, e.InheritedRowStyle.Font, v_SolidBrush, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5);
        }

        private void dgbyaopin_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            AddRowCount(dgvyaopin, e);
        }

        public void BindTable(List<string> cols, DataGridView gridview, ParamTable pt)
        {
            var table = new DataTable(pt.TableName);
            foreach (var item in cols)
            {
                table.Columns.Add(item);
            }
            table.Columns["money"].DataType = typeof(decimal);
            foreach (var item in pt.Rows)
            {
                var newrow = table.NewRow();
                foreach (var kv in item.Values)
                {
                    if (table.Columns.Contains(kv.Key))
                    {
                        newrow[kv.Key] = kv.Value;
                    }
                }
                table.Rows.Add(newrow);
            }
            var tptable = table.DefaultView;
            var totalrow = table.NewRow();
            totalrow["money"] = table.Compute("sum(money)", "");
            gridview.Tag = tptable.ToTable();
            table.Rows.Add(totalrow);
            gridview.DataSource = table;
        }

        private void dgvfeiyong_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            AddRowCount(dgvfeiyong, e);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            try
            {
                var table = (dgvfeiyong.Tag as DataTable).DefaultView;
                table.RowFilter = txtybjyhm.Text;
                dgvfeiyong.DataSource = table;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            var strs = comboBox1.SelectedItem.ToString().Split('.');
            var callparam = new HangZhouYHQYBTradeParms(100102);
            callparam[0]["match_type"] = strs[0];
            callparam.SetOutResult(strs[2]);
            Util.YBCall(callparam);
            WriteXmlFile(strs[1], callparam.OutputTable[strs[2]]);
        }

        public void WriteXmlFile(string name, ParamTable table)
        {
            MessageBox.Show("下载到 " + table.Rows.Count + " 条项目");
            table.TableView.WriteXml(Application.StartupPath + "\\" + name + ".xml", XmlWriteMode.WriteSchema);
        }

        public string replace(string value)
        {
            return value.Replace("<", "&lt;").Replace(">", "&gt;").Replace("&", "©");
        }

        DataTable temptable;
        private void button10_Click(object sender, EventArgs e)
        {
            var strs = comboBox1.SelectedItem.ToString().Split('.');
            if (!File.Exists(Application.StartupPath + "\\" + strs[1] + ".xml"))
            {
                MessageBox.Show("没有找到下载的" + strs[1]);
                return;
            }
            var table = new DataTable();
            temptable = new DataTable();
            table.ReadXml(Application.StartupPath + "\\" + strs[1] + ".xml");
            temptable.ReadXml(Application.StartupPath + "\\" + strs[1] + ".xml");
            dgvyibaoml.DataSource = table;
            toolStripStatusLabel1.Text = "总计: " + table.Rows.Count;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            
            int c = 0;
            foreach (var item in txtjbdel.Lines)
            {
                var callparam = new HangZhouYHQYBTradeParms(100104);
                callparam[0]["serial_match"] = item;
                callparam[0]["audit_flag"] = "1";
                callparam[0]["edit_staff"] = "DBA";
                callparam[0]["edit_man"] = "DBA";

                try
                {
                    Util.YBCall(callparam);
                    c++;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            MessageBox.Show("删除成功" + c + " 个");
        }

        private void button12_Click(object sender, EventArgs e)
        {

        }

        private void button13_Click(object sender, EventArgs e)
        {
            downmatched(dgvjb, "2");
        }

        private void button14_Click(object sender, EventArgs e)
        {
            loadmatched(dgvjb, "2", textBox4.Text);
        }

        private void dgvjb_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            AddRowCount(dgvjb, e);
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            var tablename = "calc_fee_info";
            //var callparam = new HangZhouYHQYBTradeParms(200016);
            var callparam = new HangZhouYHQYBTradeParms(120503);
            callparam[0]["hospital_id"] = BXLBXX.YBYYDM;// 	医疗机构编码
            callparam[0]["serial_no"] = txtybjyhm.Text;//	业务序列号
            callparam[0]["calc_flag"] = "0";
            callparam.SetOutResult(tablename);
            Util.YBCall(callparam);
            var table = callparam.OutputTable[tablename].TableView;
            dgvfeiyong.DataSource = table;
            dgvfeiyong.Tag = table;
        }

        private void textBox1_Click(object sender, EventArgs e)
        {
            if (txtybjyhm.Text == txtybjyhm.Tag.ToString())
            {
                txtybjyhm.Text = "";
            }
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            if (txtybjyhm.Text == "")
            {
                txtybjyhm.Text = txtybjyhm.Tag.ToString();
            }
        }

        public void AddLineNo(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            try
            {
                //添加行号 
                SolidBrush v_SolidBrush = new SolidBrush((sender as DataGridView).RowHeadersDefaultCellStyle.ForeColor);
                int v_LineNo = 0;
                v_LineNo = e.RowIndex + 1;

                string v_Line = v_LineNo.ToString();

                e.Graphics.DrawString(v_Line, e.InheritedRowStyle.Font, v_SolidBrush, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5);

            }
            catch (Exception ex)
            {
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            var read = new DataRead();
            
            var folder = new FolderBrowserDialog();
            folder.ShowNewFolderButton = true;
            if (folder.ShowDialog() == DialogResult.OK)
            {
                var entrys = read.GetTable("SELECT (SELECT ybyydm FROM yb_BXLBXX x WHERE x.ylbxid = t.ylbxid) YBYYDM,    " +
                   "       t.ybjyhm, " +
                   "       to_char(t.bdjyrq, 'yyyy-MM-dd') YBJSRQ, " +
                   "       f_getzyje(t.zyjsid,'FYZE') FYZE, " +
                   "       f_getzyje(t.zyjsid,'BXZE') BXZE  " +
                   "  FROM yb_zyjsxx t " +
                   " WHERE ylbxid = 105 " +
                   "   AND to_char(bdjyrq, 'yyyy-MM') = '{0:yyyy-MM}' AND trim(t.ybrylb) not in ('64','65','66','67')  " +
                   " ORDER BY t.bdjyrq ASC",
                   dateTimePicker1.Value);
                using (StreamWriter sw = new StreamWriter(folder.SelectedPath + "\\47011666-5城镇职工医院住院数据上报" + dateTimePicker1.Text + ".txt", false, Encoding.UTF8))
                {
                    foreach (var item in entrys)
                    {
                        sw.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}", item["YBYYDM"], item["YBJYHM"], item["YBJSRQ"], item["FYZE"], item["BXZE"]));
                    }
                    MessageBox.Show("城镇职工住院结算数据导出成功,条数: " + entrys.Count);
                }
                entrys = read.GetTable("SELECT (SELECT ybyydm FROM yb_BXLBXX x WHERE x.ylbxid = t.ylbxid) YBYYDM,    " +
                   "       t.ybjyhm, " +
                   "       to_char(t.bdjyrq, 'yyyy-MM-dd') YBJSRQ, " +
                   "       f_getzyje(t.zyjsid,'FYZE') FYZE, " +
                   "       f_getzyje(t.zyjsid,'BXZE') BXZE  " +
                   "  FROM yb_zyjsxx t " +
                   " WHERE ylbxid = 105 " +
                   "   AND to_char(bdjyrq, 'yyyy-MM') = '{0:yyyy-MM}' AND trim(t.ybrylb) in ('64','65','66','67')  " +
                   " ORDER BY t.bdjyrq ASC",
                   dateTimePicker1.Value);
                using (StreamWriter sw = new StreamWriter(folder.SelectedPath + "\\47011666-5城乡居民医院住院数据上报" + dateTimePicker1.Text + ".txt", false, Encoding.UTF8))
                {
                    foreach (var item in entrys)
                    {
                        sw.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}", item["YBYYDM"], item["YBJYHM"], item["YBJSRQ"], item["FYZE"], item["BXZE"]));
                    }
                    MessageBox.Show("城乡居民住院结算数据导出成功,条数: " + entrys.Count);
                }
                entrys = read.GetTable("SELECT (SELECT ybyydm FROM yb_BXLBXX x WHERE x.ylbxid = t.ylbxid) YBYYDM,    " +
                   "       t.ybjyhm,     " +
                   "       to_char(t.bdjyrq, 'yyyy-MM-dd') YBJSRQ, " +
                   "       f_getmzje(t.mzjsid,'FYZE') FYZE, " +
                   "       f_getmzje(t.mzjsid,'BXZE') BXZE  " +
                   "  FROM yb_mzjsxx t " +
                   " WHERE ylbxid = 105 " +
                   "   AND to_char(bdjyrq, 'yyyy-MM') = '{0:yyyy-MM}' AND trim(t.ybrylb) not in ('64','65','66','67') " +
                   " ORDER BY t.bdjyrq ASC",
                   dateTimePicker1.Value);
                using (StreamWriter sw = new StreamWriter(folder.SelectedPath + "\\47011666-5城镇职工医院门诊数据上报" + dateTimePicker1.Text + ".txt", false, Encoding.UTF8))
                {
                    foreach (var item in entrys)
                    {
                        sw.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}", item["YBYYDM"], item["YBJYHM"], item["YBJSRQ"], item["FYZE"], item["BXZE"]));
                    }
                    MessageBox.Show("城镇职工门诊结算数据导出成功,条数: " + entrys.Count);
                }
                entrys = read.GetTable("SELECT (SELECT ybyydm FROM yb_BXLBXX x WHERE x.ylbxid = t.ylbxid) YBYYDM,    " +
                   "       t.ybjyhm,     " +
                   "       to_char(t.bdjyrq, 'yyyy-MM-dd') YBJSRQ, " +
                   "       f_getmzje(t.mzjsid,'FYZE') FYZE, " +
                   "       f_getmzje(t.mzjsid,'BXZE') BXZE  " +
                   "  FROM yb_mzjsxx t " +
                   " WHERE ylbxid = 105 " +
                   "   AND to_char(bdjyrq, 'yyyy-MM') = '{0:yyyy-MM}' AND trim(t.ybrylb) in ('64','65','66','67') " +
                   " ORDER BY t.bdjyrq ASC",
                   dateTimePicker1.Value);
                using (StreamWriter sw = new StreamWriter(folder.SelectedPath + "\\47011666-5城乡居民医院门诊数据上报" + dateTimePicker1.Text + ".txt", false, Encoding.UTF8))
                {
                    foreach (var item in entrys)
                    {
                        sw.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}", item["YBYYDM"], item["YBJYHM"], item["YBJSRQ"], item["FYZE"], item["BXZE"]));
                    }
                    MessageBox.Show("城乡居民门诊结算数据导出成功,条数: " + entrys.Count);
                }
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (temptable == null)
            {
                MessageBox.Show("请先加载数据");
                return;
            }
            var strs = comboBox1.SelectedItem.ToString().Split('.');
            var sqlcontent = ExportSQL.Export(strs[0], temptable);
            var open = new SaveFileDialog();
            open.Filter = "(*.csv)|.csv";
            open.FileName = strs[1];
            if (open.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(open.FileName, sqlcontent, Encoding.Default);
            }
        }

        private void dgvyibaoml_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button16_Click(object sender, EventArgs e)
        {
            #region 提取医疗费用结算费用明细(120803) 惠民

            try
            {
                var callparam = new HangZhouYHQYBTradeParms(120803);
                callparam[0]["hospital_id"] = BXLBXX.YBYYDM;// 	医疗机构编码
                callparam[0]["serial_no"] = txtjbdel.Text;//	业务序列号
                callparam[0]["stat_type"] = "";//	收费项目类型
                callparam.SetOutResult("inhospitalinfo");
                Util.YBCall(callparam);
                ParamTable table;
                if (callparam.GetOutTable(out table, "inhospitalinfo"))
                {
                    var list = new List<GUAHAOYJS_OUTGUAHAOYJSFEIYONGMXZFXX>();
                    foreach (var item in table.Rows)
                    {
                        var zfxx = new GUAHAOYJS_OUTGUAHAOYJSFEIYONGMXZFXX();
                        zfxx.CHUFANGXH = "";//	处方序号
                        zfxx.MINGXIXH = item["hos_serial"];//	明细序号
                        zfxx.YIBAODM = item["item_code"].ToUpper();//	医保代码
                        zfxx.YIBAOZFBL = item["scale"];//	医保自付比例
                        zfxx.XIANGMUXJ = "0";//	项目限价
                        zfxx.YIBAOXMGL = item["stat_type"];//	医保项目归类
                        zfxx.YIBAODJ = zfxx.YIBAOZFBL == "1" ? "3" : (zfxx.YIBAOZFBL == "0" ? "1" : "2");//	医保等级
                        if (item["money"] == item["pay_first"])
                        {
                            zfxx.ZIFEIJE = item["pay_first"];//	自费金额
                            zfxx.ZILIJE = "0";//自理金额
                        }
                        else
                        {
                            zfxx.ZIFEIJE = "0";//自费金额
                            zfxx.ZILIJE = item["pay_first"];//自理金额
                        }
                        zfxx.BEIZHUXX = item["stat_name"];//	备注信息
                        list.Add(zfxx);

                    }
                    var output = new GUAHAOYJS_OUT();
                    output.Items = new object[2];
                    output.Items[1] = new GUAHAOYJS_OUTGUAHAOYJS { FEIYONGMXZFXX = list.ToArray() };
                    using (MemoryStream ms = new MemoryStream())
                    {
                        XmlSerializerNamespaces xmlSerializerNamespaces = new XmlSerializerNamespaces();
                        xmlSerializerNamespaces.Add("", "");
                        new XmlSerializer(typeof(GUAHAOYJS_OUT)).Serialize(new System.Xml.XmlTextWriter(ms, Encoding.UTF8), output, xmlSerializerNamespaces);
                        ms.Flush();
                        ms.Position = 0;
                        using (StreamReader sr = new StreamReader(ms))
                        {
                            Debug.WriteLine(sr.ReadToEnd());

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            #endregion
        }

        public string GetFYLX(string lx)
        {
            switch (lx)
            {
                case "0": return "诊疗项目";
                case "1": return "西药";
                case "2": return "中成药";
                case "3": return "中草药";
                default: return "其它";
            }
        }
    }
}
